// 配置基础URL
const baseURL = 'https://gvr.home.noahyin.site:81'
const timeout = 15000

// 处理图片/文件URL
const handleResourceUrl = (url) => {
  if (!url) return url
  // 判断是否为绝对路径（是否包含协议头）
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url
  }
  // 相对路径则拼接baseURL
  return baseURL + url
}

// 请求拦截器
const requestInterceptor = (config) => {
  // 从storage获取token
  const token = uni.getStorageSync('token')
  if (token) {
    config.header = {
      ...config.header,
      'X-Token': token  // 修改为X-Token
    }
  }
  return config
}

// 响应拦截器
const responseInterceptor = (response) => {
  const { statusCode, data } = response
  // HTTP状态码判断
  if (statusCode !== 200) {
    return Promise.reject(new Error(`HTTP错误，状态码: ${statusCode}`))
  }

  // 根据GVR接口规范处理响应
  if (data.code === 0) {  
    // 处理 token
    const token = data.attach?.token
    if (token) {
      uni.setStorageSync('token', token)
      console.log('Token已更新:', token)
    }

    // ���他处理逻辑...
    if (typeof data.data === 'object') {
      const processUrls = (obj) => {
        for (let key in obj) {
          if (typeof obj[key] === 'string' && 
              (key.includes('avatar') || key.includes('image') || key.includes('file'))) {
            obj[key] = handleResourceUrl(obj[key])
          } else if (typeof obj[key] === 'object') {
            processUrls(obj[key])
          }
        }
      }
      processUrls(data.data)
    }
    return data.data
  }
  
  // token失效处理
  if (data.code === 401) {
    uni.removeStorageSync('token')
    uni.reLaunch({
      url: '/pages/login/login'
    })
    return Promise.reject(new Error('token已失效，请重新登录'))
  } else {
	  return data
  }
  // // 其他错误处理
  // return Promise.reject(new Error(data.msg || '未知错误'))
}

// 封装请求方法
const request = (options = {}) => {
	
  options.url= baseURL + options.url
  console.log('请求地址=====' + options.url)
  // 组合请求参数
  const config = {
    timeout,
    header: options.header || {},
    method: options.method || 'GET',
    ...options
  }

  // 请求拦截
  const interceptedConfig = requestInterceptor(config)
  console.log('请求数据日志=====' + JSON.stringify(config))
  uni.showLoading({
	  title:'加载中',
	  mask: true
  })
  // 发起请求
  return new Promise((resolve, reject) => {
    uni.request({
      ...interceptedConfig,
      success: (res) => {
        try {
		  console.log('全部数据日志=====' + JSON.stringify(res))
          const result = responseInterceptor(res)
		  console.log('data数据日志=====' + JSON.stringify(result))
          resolve(result)
        } catch (error) {
          reject(error)
        }
      },
      fail: (err) => {
        console.error('请求失败:', err)
        reject(new Error(err.errMsg || '请求失败'))
      },
	  complete: (e)=> {
		  console.log('隐藏loadding')
		  uni.hideLoading()
	  }
    })
  })
}

// 封装文件上传方法
export const uploadFile = (filePath, formData = {}) => {
  return new Promise((resolve, reject) => {
    const token = uni.getStorageSync('token')
    uni.uploadFile({
      url: baseURL + '/api/file/upload',
      filePath,
      name: 'file',
      formData,
      header: {
        'X-Token': token
      },
      success: (res) => {
        try {
          const data = JSON.parse(res.data)
          if (data.code === 0) {
            resolve(handleResourceUrl(data.data))
          } else {
            reject(new Error(data.msg || '上传失败'))
          }
        } catch (error) {
          reject(error)
        }
      },
      fail: (err) => {
        console.error('上传失败:', err)
        reject(new Error(err.errMsg || '上传失败'))
      }
    })
  })
}

// 封装常用请求方法
export const get = (url, params = {}, header = {}) => {
  return request({
    url,
    method: 'GET',
    data: params,
    header
  })
}

export const post = (url, data = {}, header = {}) => {
  return request({
    url,
    method: 'POST',
    data,
    header
  })
}

export const put = (url, data = {}, header = {}) => {
  return request({
    url,
    method: 'PUT',
    data,
    header
  })
}

export const del = (url, data = {}, header = {}) => {
  return request({
    url,
    method: 'DELETE',
    data,
    header
  })
}

export default request 